# coding=utf-8

import logging
import telnetlib
import socket
import os

from pexpect import run

from config import BeetleConfig

log = logging.getLogger(__name__)


class BasicServiceCheck(object):

    @staticmethod
    def check_mongodb():
        ok = BasicServiceCheck.check_port('27017')
        return ok

    @staticmethod
    def check_oracle():
        ok = BasicServiceCheck.check_port('1521')
        return ok

    @staticmethod
    def check_mysql():
        output, status = run('/bin/bash -c "service mysqld status"', withexitstatus=1, timeout=None)

        if status == 0 and str(output).find('MySQL running') > 0:
            ok = BasicServiceCheck.check_port('3306')
            return ok
        else:
            return False

    @staticmethod
    def check_rabbitmq():
        ok = BasicServiceCheck.check_port('5672')
        return ok

    @staticmethod
    def check_cassandra():

        sh = '/bin/bash -c "%s"' % (BeetleConfig.CASSANDRA_HOME_PATH + '/bin/nodetool status')
        output, status = run(sh, withexitstatus=1, timeout=None)
        if status == 0:
            if str(output).find('UN  127.0.0.1') > 0:
                return True
            else:
                return False
        else:
            return False

    @staticmethod
    def check_redis():
        check_ports = [
                        {'port': 6379, 'error': 'gzidc redis access failed [172.0.0.1:6379]'},
                        {'port': 16379, 'error': 'usaws redis access failed [172.0.0.1:16379]'},
                        {'port': 26379, 'error': 'euaws redis access failed [172.0.0.1:26379]'},
                        {'port': 36379, 'error': 'auaws redis access failed [172.0.0.1:36379]'}
                      ]
        return BasicServiceCheck.check_ports(check_ports)

    @staticmethod
    def check_zookeeper():
        check_ports = [
                        {'port': 2181, 'error': 'gzidc zookeeper access failed [172.0.0.1:2181]'},
                        {'port': 12181, 'error': 'usaws zookeeper access failed [172.0.0.1:12181]'},
                        {'port': 22181, 'error': 'euaws zookeeper access failed [172.0.0.1:22181]'},
                        {'port': 32181, 'error': 'auaws zookeeper access failed [172.0.0.1:32181]'}
                      ]
        return BasicServiceCheck.check_ports(check_ports)

    @staticmethod
    def check_ports(check_ports):
        results = []
        for port in check_ports:
            ok = BasicServiceCheck.check_port(port['port'])
            if not ok:
                results.append(port['error'])
        return results

    @staticmethod
    def check_port(port, ipaddress='127.0.0.1', timeout=1):
        try:
            t = telnetlib.Telnet(host=ipaddress, port=port, timeout=timeout)
        except:
            return False
        else:
            return True
        finally:
            try:
                if t:
                    t.close()
            except:
                pass

    @staticmethod
    def check_aliveness(port, ip='127.0.0.1'):
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.settimeout(1)
        try:
            sk.connect((ip, port))
            print 'service is OK!'
            return True
        except Exception:
            print 'service is NOT OK!'
            return False
        finally:
            try:
                if sk:
                    sk.close()
            except:
                pass
        return False


class AppServiceCheck(object):

    @staticmethod
    def check_app_dir():
        results = []
        areas = os.listdir(BeetleConfig.APP_DEPLOY_BASE_PATH)
        for area in areas:
            if area.startswith('uc.'):
                area_home = '%s/%s' % (BeetleConfig.APP_DEPLOY_BASE_PATH, area)
                if os.path.isdir(area_home):
                    apps = os.listdir(area_home)
                    for app in apps:
                        if app.startswith('php_'):
                            app_home = '%s/%s' % (area_home, app)
                            fs = os.listdir(app_home)
                            if len(fs) <= 0:
                                results.append('%s is empty' % app_home)
                        if app.startswith('tomcat_'):
                            app_home = '%s/%s/webapps' % (area_home, app)
                            fs = os.listdir(app_home)
                            if len(fs) <= 0:
                                results.append('%s is empty' % app_home)

                        if app.startswith('ad_'):
                            app_home = '%s/%s' % (area_home, app)
                            fs = os.listdir(app_home)
                            if len(fs) <= 0:
                                results.append('%s is empty' % app_home)
        return results


if __name__ == '__main__':
    print 'zoodeeper', BasicServiceCheck.check_zookeeper()

    print 'redis', BasicServiceCheck.check_redis()

    print 'rabbitmq', BasicServiceCheck.check_rabbitmq()

    print 'mysql', BasicServiceCheck.check_mysql()

    print 'oracle', BasicServiceCheck.check_oracle()

    print 'mongodb', BasicServiceCheck.check_mongodb()

    #print 'cassandra', BasicServiceCheck.check_cassandra()

    print 'app_empty', AppServiceCheck.check_app_dir()